package com.lp.search.component.listener;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lp.model.constants.MQConstants;
import com.lp.search.service.IArticleSearchService;
import com.lp.search.service.IUserSearchService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ArticleListener {

    @Autowired
    private IArticleSearchService articleSearchService;

    @Autowired
    private IUserSearchService userSearchService;

    @Autowired
    private ObjectMapper objectMapper;

    @RabbitListener(queues = MQConstants.ES_ARTICLE_INSERT_QUEUE)
    public void articleInsertMsg(String msg) {
        log.info("MQ 消息: 新增文章 {}", msg);
        //1.解析数据
        Long articleId = objectMapper.convertValue(msg, new TypeReference<Long>() {});
        //2.新增文章文档
        articleSearchService.insertByArticleId(articleId);
        log.info("MQ 文章新增同步到 es 完成");
    }

    @RabbitListener(queues = MQConstants.ES_ARTICLE_DEL_QUEUE)
    public void articleDelMsg(String msg) {
        log.info("MQ 消息: 删除文章 {}", msg);
        //1.解析数据
        Long articleId = objectMapper.convertValue(msg, new TypeReference<Long>() {});
        //2.删除文章文档
        articleSearchService.delByArticleId(articleId);
        log.info("MQ 文章删除同步到 es 完成");
    }

    @SneakyThrows
    @RabbitListener(queues = MQConstants.ES_ARTICLE_UPDATE_QUEUE)
    public void articleUpdateMsg(String msg) {
        log.info("MQ 消息: 修改文章 {}", msg);
        //1.解析数据
        Long articleId = objectMapper.readValue(msg, Long.TYPE);
        //2.修改文章文档
        articleSearchService.updateByArticleId(articleId);
        log.info("MQ 文章修改同步到 es 完成");
    }

    @SneakyThrows
    @RabbitListener(queues = MQConstants.ES_USER_UPDATE_QUEUE)
    public void userUpdateMsg(String msg) {
        log.info("MQ 消息: 修改用户信息 {}", msg);
        //1.解析数据
        Long userId = objectMapper.readValue(msg, Long.TYPE);
        //2.修改用户信息文档
        userSearchService.updateByUserId(userId);
        log.info("MQ 用户信息修改同步到 es 完成");
    }

}
